
package com.roncoo.config;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roncoo.order.dao.UserCourseMapper;
import com.roncoo.order.entity.OrderInfo;
import com.roncoo.order.entity.User;
import com.roncoo.order.entity.UserCourse;
import com.roncoo.order.service.OrderInfoService;
import com.roncoo.order.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * @ProjectName: lnsf2019_project
 * @Package: com.lnsf.payment.controller
 * @ClassName: PayController
 * @Author: Mr.chenzy
 * @Description: ${description}
 * @Date: 2019/7/30 9:49
 * @Version: 1.0
 */
@Controller
public class PayController {


    public static int odid = 0;
    public static int userId = 0;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private UserService userService;
    @Resource
    private UserCourseMapper userCourseMapper;

    @RequestMapping("/toPay")
    @ResponseBody/*String orderno,Integer maney*/
    public String toPay(String orderno,Integer money) throws Exception {
 //       System.out.println(orderId);
//        System.out.println(orderno+"==="+maney);
//        System.out.println(2);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderno + "\","
                    + "\"total_amount\":\"" + money + "\","
                    + "\"subject\":\"" + "请你支付" + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result;
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //System.out.println("*********************\n返回结果为：" + result);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }


    /**待支付
     *
     * @return
     */

    @RequestMapping("/toPay2")
    @ResponseBody/*String orderno,Integer maney*/
    public String toPay(String orderno,Integer money,Integer orderId) throws Exception {
        odid=orderId;
        System.out.println(odid);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://localhost:8898/order/updStatus");
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderno + "\","
                    + "\"total_amount\":\"" + money + "\","
                    + "\"subject\":\"" + "请你支付" + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result;
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //System.out.println("*********************\n返回结果为：" + result);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /**
     * vip支付
     * @return
     */

    @RequestMapping("/toPaySVip")
    @ResponseBody/*String orderno,Integer maney*/
    public String toPaySVip(String orderno,Integer money,Integer userid) throws Exception {
        userId=userid;
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://localhost:8898/order/updVipStatus");
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderno + "\","
                    + "\"total_amount\":\"" + money + "\","
                    + "\"subject\":\"" + "请你支付" + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result;
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //System.out.println("*********************\n返回结果为：" + result);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("updVipStatus")
    public String updVipStatus(){
        //将当前用户vip状态修改
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",userId);
        User user = new User();
        user.setIsSvip(1);
        boolean update = userService.update(user, queryWrapper);
        return "redirect:http://localhost:8080/vip#/SVIP";
    }


    @GetMapping("updStatus")
    public String updStatus(){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        //修改订单状态
        queryWrapper.eq("order_id",odid);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus("1");
        orderInfo.setPayTime(LocalDate.now());//修改时间
        boolean update = orderInfoService.update(orderInfo, queryWrapper);

        //把购买的课程添加到用户课程表中
        OrderInfo byId = orderInfoService.getById(odid);
        UserCourse userCourse = new UserCourse();
        userCourse.setUserId(byId.getUserNo());
        userCourse.setCourseId(byId.getCourseId());
        userCourse.setCourseName(byId.getCourseName());
        //添加
        int insert = userCourseMapper.insert(userCourse);
        if (update){
            return "redirect:http://localhost:8080/#/myCourses";
        }else {
            return "redirect:http://localhost:8080/#/failure";
        }
    }




    @RequestMapping("alipay/callback/return_sult")
    public String toIndex() {
        return "index";
    }
}
